package com.example.tys.daggermvp.network.okhttpclient;

import com.example.tys.daggermvp.Application.DaggerApplication;
import com.example.tys.daggermvp.MyApp;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author tys
 * @date 2018/4/22
 */

public class CacheOkHttpClient extends BaseOkHttpClient {

    private static final long CACHE_SIZE = 1024;
    private final Interceptor mCacheControlInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder()
                    //通过okhttp request看不到head参数， 但是tomcat中可以看到参数已经添加到head中
                    .header("setHead-cache", "setHead")
                    .addHeader("addHead-cache", "addHead")
                    .build();
            Response originalResponse = chain.proceed(request);
            return originalResponse.newBuilder()
                    .header("Cache-Control", "responseHead")
                    .build();
        }
    };

    @Override
    public OkHttpClient.Builder customize(OkHttpClient.Builder builder) {
        File cacheFile = new File(MyApp.getInstance().getCacheDir(), "appBase");
        Cache cache = new Cache(cacheFile, CACHE_SIZE);
        builder.cache(cache);
        builder.addNetworkInterceptor(mCacheControlInterceptor);
        return builder;
    }
}
